package com.lkd.handler;


import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class VMSupplyHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;
    @Autowired
    private VMService vmService;
    @Override
    public void process(String jsonMsg) throws IOException {
        //接受补货消息，完成自动补货
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        //判断对象是否为空
        if (supplyContract==null||supplyContract.getInnerCode()==null||supplyContract.getSupplyData().size()<=0){
            return;
        }

        //查询售货机是否存在
        VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
        if (vmInfo==null){
            return;
        }
        //获取工单量最少的用户
        Integer userId = taskService.getLeastUser(vmInfo.getRegionId(), false);
        //调用补货方法
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setUserId(userId);
        taskViewModel.setDesc(jsonMsg);
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setAssignorId(0);
        taskViewModel.setCreateType(0);
        //设置补货详情
        taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(s->{
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setSkuId(s.getSkuId());
            taskDetailsViewModel.setSkuName(s.getSkuName());
            taskDetailsViewModel.setSkuImage(s.getSkuImage());
            taskDetailsViewModel.setExpectCapacity(s.getCapacity());
            taskDetailsViewModel.setChannelCode(s.getChannelId());
            return taskDetailsViewModel;
        }).collect(Collectors.toList()));

        taskService.createTask(taskViewModel);
    }



}
